package com.wgke.bluetooth.ui;

import android.bluetooth.BluetoothDevice;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.newmobiler.android.ui.adapter.CellAdapter;
import com.newmobiler.android.ui.adapter.cell.MultiCell;
import com.newmobiler.android.ui.adapter.divider.RVItemDivider;
import com.newmobiler.android.ui.adapter.viewholder.RVViewHolder;
import com.wgke.bluetooth.R;
import com.wgke.bluetooth.beans.CommandBean;
import com.wgke.bluetooth.event.EventReadBean;
import com.wgke.bluetooth.event.EventWriteBean;
import com.wgke.bluetooth.tools.BtMsg;
import com.wgke.bluetooth.ui.dialog.ChooseDialog;
import com.wgke.bluetooth.ui.dialog.WheelDialog;
import com.wgke.bluetooth.utils.BluetoothGattManager;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.vm.RWVM;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class RWActivity extends BaseActivity<RWVM> {
    CellAdapter cellAdapter;
    EditText et;
    int height = 0;


    @Override
    public int layoutId() {
        return R.layout.activity_rw;
    }

    @Override
    public void initView() {
        vm.loadFileRes();
        cellAdapter = new CellAdapter(this);
        RecyclerView rv = findViewById(R.id.rv);
        et = findViewById(R.id.etInput);
        rv.setLayoutManager(new GridLayoutManager(this, 3));
        rv.setAdapter(cellAdapter);
        rv.addItemDecoration(new RVItemDivider(R.color.black_999, 1));
        vm.mList.observe(this, this::setData);
        findViewById(R.id.tvSend).setOnClickListener(this::onClickView);
        TextView readInput = findViewById(R.id.readInput);
        TextView tvCount = findViewById(R.id.tvCount);
        vm.content.observe(this, readInput::setText);
        vm.readCount.observe(this, integer -> tvCount.setText("" + integer));
        String uuid = getIntent().getStringExtra("uuid");
        postDelayed(500, () -> vm.readByService(uuid));
        postDelayed(1000, () -> vm.setNotice(true));
        rv.post(() -> {
            height = rv.getHeight();
            cellAdapter.notifyDataSetChanged();
        });
    }

    private void setData(List<CommandBean> list) {
        for (CommandBean bean : list) {
            cellAdapter.addDataAtLast(MultiCell.convert(R.layout.item_btn_type, 1, bean, (h, c) -> {
                h.setVisibility(R.id.tvBtn, View.VISIBLE);
                h.setVisibility(R.id.llBtn2, View.GONE);
                h.setVisibility(R.id.llBtn2, View.GONE);
                int position = h.getAdapterPosition();
                if (position > 2) {
                    int r = R.drawable.border_white_bg_t;
                    h.setBackgroundRes(R.id.tvBtn, r);
                } else {
                    h.setBackgroundRes(R.id.tvBtn, R.drawable.border_white_bg);
                }

                int size = c.name.length();
                h.setText(R.id.tvBtn, size > 3 ? (c.name.substring(0, size / 2) + "\n" + c.name.substring(size / 2, size)) : c.name);
                h.setOnClickListener(R.id.tvBtn, v -> {
                    onClickCmd(c);
                });
                changeHeight(h, list.size());
            }));
        }
    }

    /**
     * 设置高度，让其满屏
     */
    private void changeHeight(RVViewHolder holder, int size) {
        if (size > 11 && size < 19 && height != 0) {
            ViewGroup.LayoutParams params = holder.getView(R.id.clGroup).getLayoutParams();
            params.height = height / ((size + 2) / 3) - 1;
            holder.getView(R.id.clGroup).setLayoutParams(params);
        }
    }

    private void onClickCmd(CommandBean bean) {
        if (bean.params == null && bean.scope == null) {
            et.setText(vm.getCmd(bean));
        } else if (bean.params == null && !TextUtils.isEmpty(bean.scope)) {
            String[] scopeArr = bean.scope.split(",");
            if (scopeArr.length == 1) {
                showSingle(bean, scopeArr[0]);
            } else {
                showType(bean, scopeArr);
            }
        } else if (bean.params != null && !bean.params.isEmpty()) {
            String scope = bean.params.get(0).scope;
            boolean s = true;
            for (CommandBean c1 : bean.params) {
                if (!TextUtils.equals(scope, c1.scope)) {
                    s = false;
                }
            }
            if (s) {
                scope = bean.params.get(0).value + "-" + bean.params.get(bean.params.size() - 1).value + "," + scope;
                String[] names = new String[bean.params.size()];
                for (int i = 0; i < names.length; i++) {
                    names[i] = bean.params.get(i).name;
                }
                showType(bean, scope.split(","), names);
            }
        }
    }

    private void showSingle(CommandBean bean, String str) {
        String title = TextUtils.isEmpty(bean.doc) ? bean.name : bean.doc;
        ChooseDialog dialog = new ChooseDialog(this, vm.rangeStringToIntArray(str), title);
        dialog.setCallback((index, value) -> setEt(vm.getCmd(bean, value)));
        dialog.show();
    }

    private void showType(CommandBean bean, String[] str) {
        String title = TextUtils.isEmpty(bean.doc) ? bean.name : bean.doc;
        WheelDialog dialog = new WheelDialog(this, str, title);
        dialog.setCallback((arr) -> setEt(vm.getCmd(bean, arr)));
        dialog.show();
    }

    private void showType(CommandBean bean, String[] str, String[] name) {
        String title = TextUtils.isEmpty(bean.doc) ? bean.name : bean.doc;
        WheelDialog dialog = new WheelDialog(this, str, name, title);
        dialog.setCallback((arr) -> setEt(vm.getCmd(bean, arr)));
        dialog.show();
    }


    private void setEt(String str) {
        et.setText(str);
        et.setSelection(str.length());
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        et.startAnimation(shake);
    }

    private void onClickView(View v) {
        String data = et.getText().toString();
        if (TextUtils.isEmpty(data) || data.trim().isEmpty()) {
            ToastUtil.showLongMsg("请输入数据");
            return;
        }
        byte[] bytes = BtMsg.hexStringToByteArray(data);
        if (bytes == null) {
            ToastUtil.showLongMsg("数据非法，HEX格式！！！");
            return;
        }
        vm.writeBytes(bytes);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageReadEvent(EventReadBean event) {
        vm.readBytes(event.isRead, event.bytes);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageWriteEvent(EventWriteBean event) {
        ToastUtil.showLongMsg(event.success ? "写入成功！" : "错误" + event.msg);
    }
}
